package handler

import (
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"microdemo/restful/bff/internal/logic"
	"microdemo/restful/bff/internal/svc"
	"microdemo/restful/bff/internal/types"
	"net/http"

	"github.com/zeromicro/go-zero/rest/httpx"
)

func GetHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 打印 User-Agent 信息，用于验证路由中间件作用范围
		logx.Info(fmt.Sprintf("User-Agent 为：%s", r.Header.Get("User-Agent")))
		var req types.BffReq
		response := NewResponse()
		if err := httpx.Parse(r, &req); err != nil {
			// 自定义统一响应的处理函数
			response.Error(r.Context(), w, err)
			return
		}
		// 调用 logic
		l := logic.NewGetLogic(r.Context(), svcCtx)
		resp, err := l.Get(&req)
		// 自定义统一响应的处理函数
		response.Result(r.Context(), w, resp, err)
	}
}

func AddUserHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.UserAdd
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewGetLogic(r.Context(), svcCtx)
		resp, err := l.AddUserHandler(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}

func ModifyUserHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.UserModify
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		l := logic.NewGetLogic(r.Context(), svcCtx)
		resp, err := l.ModifyUserHandler(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}

func DeletedUserHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.IdInt64
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewGetLogic(r.Context(), svcCtx)
		resp, err := l.DeletedUserHandler(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}